//
//  NewFeatureViewController.swift
//  新浪微博
//
//  Created by yzl on 15/8/2.
//  Copyright © 2015年 yjc. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"

class NewFeatureViewController: UICollectionViewController {
    // 图片数
    let iconCount = 4
    
/// 重写init方法,直接初始化指定布局样式
    private let layout = JCFlowLayout()
    init () {
        super.init(collectionViewLayout: layout)
    }

    required init?(coder aDecoder: NSCoder) {
       // fatalError("init(coder:) has not been implemented")
        super.init(coder: aDecoder)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

                // Register cell classes
        self.collectionView!.registerClass(NewFeatureCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        
    }
    
    
/// 自定义新特性cell
    class NewFeatureCell:UICollectionViewCell {
        
        func startClick(){
            // 发送通知。切换界面
            NSNotificationCenter.defaultCenter().postNotificationName(JCRootViewControllerSwitchNotification, object: true)
        }
        // 定义图像索引
        private var iconIndex: Int = 0 {
            didSet {
                userIconView.image = UIImage(named:"new_feature_\(iconIndex + 1)")
                startButton.hidden = true
            }
        }
        override init(frame: CGRect) {
            super.init(frame: frame)
            setupUI()
        }

        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            setupUI()
            
        }
        
        // MARK : 懒加载图片
        private lazy var userIconView = UIImageView()
        private lazy var startButton:UIButton = {
       let btn = UIButton()
        btn.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: UIControlState.Highlighted)
         btn.setTitle("开始体验", forState: UIControlState.Normal)
            btn.sizeToFit()
            // 监听按钮点击
            btn.addTarget(self, action: "startClick", forControlEvents: UIControlEvents.TouchUpInside)
            btn.hidden = true
            return btn
}()
/// MARK:开始动画
        func startButtonAnimat() {
           startButton.hidden = false
            startButton.transform = CGAffineTransformMakeScale(0, 0)
            startButton.userInteractionEnabled = false
            UIView.animateWithDuration(1.2, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 10.0, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
                self.startButton.transform = CGAffineTransformIdentity
                }) { (_ ) -> Void in
                    self.startButton.userInteractionEnabled = true
            }
       }
        
     private  func setupUI(){
        // 添加控件
       contentView.addSubview(userIconView)
        contentView.addSubview(startButton)
        // 设置约束
        userIconView.ff_Fill(contentView)
//        userIconView.translatesAutoresizingMaskIntoConstraints = false
//    contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[subview]-0-|",options:NSLayoutFormatOptions(rawValue: 0), metrics: nil, views:[ "subview":userIconView]))
//    contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[subview]-0-|",options:NSLayoutFormatOptions(rawValue: 0), metrics: nil, views:[ "subview":userIconView]))
        startButton.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: contentView, size: nil, offset:CGPoint(x: 0, y: -160))
        
//        startButton.translatesAutoresizingMaskIntoConstraints = false
//     contentView.addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
//                contentView.addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: -160))
//
        
        }
    }

           // MARK: UICollectionViewDataSource

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return iconCount
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath)as! NewFeatureCell
    
      cell.iconIndex = indexPath.item
    
        return cell
    }
//    /// MARK: 显示索引的按纽
    override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        // 获取当前显示的indexcell
        let currentcell = collectionView.indexPathsForVisibleItems().last!
        if currentcell.item == iconCount-1 {
            let cell = collectionView.cellForItemAtIndexPath(currentcell)as! NewFeatureCell
            cell.startButtonAnimat()
        }
    }
        /// MARK : 定义一个自己的flowlayout类
    private class JCFlowLayout:UICollectionViewFlowLayout {
        private override func prepareLayout() {
            itemSize = collectionView!.bounds.size
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            scrollDirection = UICollectionViewScrollDirection.Horizontal
            
         collectionView?.pagingEnabled = true
            collectionView?.showsHorizontalScrollIndicator = false
            collectionView?.bounces = false
        }
    }

    
    
}
